package com.etc.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.etc.dto.Result;
import com.etc.entity.Games;
import com.etc.entity.OrderDetail;
import com.etc.entity.OrderInfo;
import com.etc.service.impl.GamesServiceImpl;
import com.etc.service.impl.OrderDetailServiceImpl;
import com.etc.service.impl.OrderInfoServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String op = request.getParameter("op");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = "";
		Result result = new Result();
		if("add".equals(op)) {// 创建一条订单详情orderDetail，前端页面传来订单号为0表示存在购物车中，未进行提交订单以及支付等后续操作
			String orderNo = request.getParameter("orderNo");
			String gamesId = request.getParameter("gamesId");
			String customerId = request.getParameter("customerId");
			
			// 解决重复创建购物车商品
			List<Games> findGamesByCustomerId = new OrderDetailServiceImpl().findGamesByCustomerId(Integer.valueOf(customerId), orderNo, Integer.valueOf(gamesId));
			if(findGamesByCustomerId.size()==0) {
				// orderNo==0 未提交订单不生成订单号保存购物车信息
				if(!"0".equals(orderNo)) {
					//提交订单生成订单号
					orderNo="";
				}
				
				OrderDetail orderDetail = new OrderDetail();
				orderDetail.setOrderNo(orderNo);
				orderDetail.setGamesId(Integer.valueOf(gamesId));
				orderDetail.setCustomerId(Integer.valueOf(customerId));
				boolean flag = new OrderDetailServiceImpl().insertOrderDetail(orderDetail);
				if(flag) {
					result.ok(flag);
				}else {
					result.fail(0, "非重复引起的添加失败");
				}
			}else {
				result.fail(0, "查到重复数据，添加失败");
			}
			json = objectMapper.writeValueAsString(result);
		}else if ("find".equals(op)) {
			// 通过用户编号查询用户的订单详情，包括游戏信息，用于显示购物车
			String orderNo = request.getParameter("orderNo");
			String customerId = request.getParameter("customerId");
			String id = request.getParameter("gamesId");
			Integer gamesId = null;
			if(id!=null){
				gamesId = Integer.valueOf(id);
			}
			List<Games> findGamesByCustomerIdList = new OrderDetailServiceImpl().findGamesByCustomerId(Integer.valueOf(customerId), orderNo, gamesId);
			
			if(findGamesByCustomerIdList.size()!=0) {
				result.ok(findGamesByCustomerIdList);
			}else {
				result.fail(0, "查无数据");
			}
			json = objectMapper.writeValueAsString(result);
		}else if ("repeat".equals(op)) {// 查询用户的订单中是否已经存在该游戏也即用户之前是否已经购买过该游戏
			String gamesId = request.getParameter("gamesId");
			String customerId = request.getParameter("customerId");
			String status = request.getParameter("status");
			if ("0".equals(status)) {//查询未支付订单
				
			}else if ("1".equals(status)) {//查询已支付订单
				OrderDetail findInfoByStatusAndGamesIdAndCustomerId = new OrderDetailServiceImpl().findInfoByStatusAndGamesIdAndCustomerId(Integer.valueOf(status), Integer.valueOf(gamesId), Integer.valueOf(customerId));
				if(findInfoByStatusAndGamesIdAndCustomerId!=null) {
					result.ok(findInfoByStatusAndGamesIdAndCustomerId);
				}else {
					result.fail(0, "未查到");
				}
			}else if ("2".equals(status)) {//查询支付超时订单
				
			}
			
			json = objectMapper.writeValueAsString(result);
		}else if ("findByStatusAndGamesIdAndCustomerId".equals(op)) {
			String status = request.getParameter("status");
			String gamesId = request.getParameter("gamesId");
			String customerId = request.getParameter("customerId");
			
			OrderDetail findInfoByGamesIdAndCustomerId = new OrderDetailServiceImpl().findInfoByStatusAndGamesIdAndCustomerId(Integer.valueOf(status), Integer.valueOf(gamesId), Integer.valueOf(customerId));
			if(findInfoByGamesIdAndCustomerId!=null) {
				
				result.ok("已购买");
			}else {
				
				result.fail(0, "未购买");
			}
			json = objectMapper.writeValueAsString(result);
		}else if ("addOrderInfo".equals(op)) {//单条订单信息与订单详情
			// 使用14位时间戳+4位随机数
			StringBuilder str = new StringBuilder();
			// 获取当前时间
			LocalDateTime ldt = LocalDateTime.now();
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
			String dt = dtf.format(ldt);
			str.append(dt);
			// 获取四位随机数
			for (int i = 0; i < 4; i++) {
				str.append(new Random().nextInt(10));
			}
			String orderNo = str.toString();
			String customerId = request.getParameter("customerId");
			String gamesId = request.getParameter("gamesId");
			
			Games games = new GamesServiceImpl().findGamesByGamesId(Integer.valueOf(gamesId));
			BigDecimal total = games.getPrice();
			
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setOrderNo(orderNo);
			orderInfo.setTotal(total);
			orderInfo.setCustomerId(Integer.valueOf(customerId));
			// 创建一条未支付的订单信息
			boolean addOrderInfo = new OrderInfoServiceImpl().addOrderInfo(orderInfo);
			// 创建一条未支付的订单详情
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setOrderNo(orderNo);
			orderDetail.setGamesId(Integer.valueOf(gamesId));
			orderDetail.setCustomerId(Integer.valueOf(customerId));
			boolean insertOrderDetail = new OrderDetailServiceImpl().insertOrderDetail(orderDetail);
			if(addOrderInfo&&insertOrderDetail) {
				// 创建提交未支付的订单成功
				result.ok(orderNo);
			}else {
				result.fail(0, "创建提交未支付的订单失败");
			}
			json = objectMapper.writeValueAsString(result);
			
		}else if ("addMoreOrderInfo".equals(op)) {//单条订单信息与多条订单详情
			// 使用14位时间戳+4位随机数
			StringBuilder str = new StringBuilder();
			// 获取当前时间
			LocalDateTime ldt = LocalDateTime.now();
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
			String dt = dtf.format(ldt);
			str.append(dt);
			// 获取四位随机数
			for (int i = 0; i < 4; i++) {
				str.append(new Random().nextInt(10));
			}
			String orderNo = str.toString();
			String gamesIdArray = request.getParameter("gamesIdArray");
			String customerId = request.getParameter("customerId");
			String sum = request.getParameter("sum");
	
			String[] gamesIdArr = gamesIdArray.split("-");
			
			
			
//			Games games = new GamesServiceImpl().findGamesByGamesId(Integer.valueOf(gamesId));
//			BigDecimal total = games.getPrice();
			 
			  
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setOrderNo(orderNo);
			orderInfo.setTotal(new BigDecimal(sum));
			orderInfo.setCustomerId(Integer.valueOf(customerId));
			// 创建一条未支付的订单信息
			boolean addOrderInfo = new OrderInfoServiceImpl().addOrderInfo(orderInfo);
		  
			for (int i = 0; i < gamesIdArr.length; i++) {
				// 创建多条未支付的订单详情
				OrderDetail orderDetail = new OrderDetail();
				orderDetail.setOrderNo(orderNo);
				orderDetail.setGamesId(Integer.valueOf(gamesIdArr[i]));
				orderDetail.setCustomerId(Integer.valueOf(customerId));
				boolean insertOrderDetail = new OrderDetailServiceImpl().insertOrderDetail(orderDetail);
			}
		  
		  
			if(addOrderInfo) { // 创建提交未支付的订单成功（这里仅对订单信息创建成功进行判断，应该是判断订单信息创建成功和多条详情创建成功）
				result.ok(orderNo);
			}else {
				result.fail(0, "创建提交未支付的订单失败");
			}
			json = objectMapper.writeValueAsString(result);
			 

		}else if ("delete".equals(op)) {// 根据游戏编号，订单号，用户编号删除
			String gamesId = request.getParameter("gamesId");
			String orderNo = request.getParameter("orderNo");
			String customerId = request.getParameter("customerId");
			
			boolean deleteDetail = new OrderDetailServiceImpl().deleteOrderDetailByOrderNoAndGamesIdAndCustomerId(orderNo, Integer.valueOf(gamesId), Integer.valueOf(customerId));
			if(deleteDetail) {
				result.ok(deleteDetail);
			}else {
				result.fail(0, "删除失败");
			}
			json = objectMapper.writeValueAsString(result);

		}else if ("updateOrderInfoStatus".equals(op)) {// 修改订单支付状态
			String status = request.getParameter("status");
			String orderNo = request.getParameter("orderNo");
			String payTime = null;
			if("1".equals(status)) {
				// 获取当前时间
				LocalDateTime ldt = LocalDateTime.now();
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
				payTime = dtf.format(ldt);
			}
			boolean updateOrderInfoStatus = new OrderInfoServiceImpl().updateOrderInfoStatus(Integer.valueOf(status), payTime, orderNo);
			if(updateOrderInfoStatus) {
				result.ok(updateOrderInfoStatus);
			}else {
				result.fail(0, "支付状态更改失败");
			}
			json = objectMapper.writeValueAsString(result);

		}else if ("findOrderInfoByOrderNo".equals(op)) {// 通过订单号查询订单信息
			String orderNo = request.getParameter("orderNo");
			OrderInfo orderInfo = new OrderInfoServiceImpl().findOrderInfoByOrderNo(orderNo);
			if(orderInfo!=null) {
				result.ok(orderInfo);
			}else {
				result.fail(0, "未购买");
			}
			json = objectMapper.writeValueAsString(result);
			
		}
		
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(json);
	}

}
